import ua from './ua'

const callHandlers = []
const registerHandlers = []
const JCBridge = {
  call(...args) {
    callHandlers.push(args)
  },
  register(...args) {
    registerHandlers.push(args)
  },
}
const jsBridge = window.WebViewJavascriptBridge

/**
 * 获取ios 的bridge object
 * https://github.com/marcuswestin/WebViewJavascriptBridge
 * @param  {Function} initBridge [description]
 * @return {[type]}            [description]
 */
function initIosBridge(initBridge) {
  if (jsBridge) {
    return initBridge(jsBridge)
  }
  if (window.WVJBCallbacks) {
    return window.WVJBCallbacks.push(initBridge)
  }
  window.WVJBCallbacks = [initBridge]
  let doc = document
  let iframe = doc.createElement('iframe')
  iframe.style.display = 'none'
  iframe.src = 'wvjbscheme://__BRIDGE_LOADED__'
  doc.body.appendChild(iframe)
  setTimeout(() => {
    doc.body.removeChild(iframe)
  })
}

/**
 * 获取android 的bridge object
 * https://github.com/lzyzsd/JsBridge
 * @param  {Function} initBridge [description]
 * @return {[type]}            [description]
 */
function initAdrBridge(initBridge) {
  if (jsBridge) {
    return initBridge(jsBridge)
  }
  document.addEventListener('WebViewJavascriptBridgeReady', () => {
    // 后端派发时间之前会设置这个值
    initBridge(window.WebViewJavascriptBridge)
  }, false)
}

/**
 * 根据环境暴露bridge object
 * @param  {[type]} bridge [description]
 * @return {[type]}           [description]
 */
function initBridge(bridge) {
  bridge.init && bridge.init()
  if (bridge) {
    JCBridge.call = bridge.callHandler
    JCBridge.register = bridge.registerHandler

    if (callHandlers.length) {
      callHandlers.forEach(call => {
        JCBridge.call(...call)
      })
    }
    if (registerHandlers.length) {
      registerHandlers.forEach(register => {
        JCBridge.register(...register)
      })
    }
  }
}

if (ua.ios) {
  initIosBridge(initBridge)
} else if (ua.android) {
  initAdrBridge(initBridge)
}

export default JCBridge

// bridge.call  调用native提供的方法
// - bridge.call('setWebViewAttr', {}) 设置webView

